﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using EC2011_hk1_BT8_1041074_1041130_1042119;

namespace Lab8_Security.Account
{
    public partial class Login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            RegisterHyperLink.NavigateUrl = "Register.aspx?ReturnUrl=" + HttpUtility.UrlEncode(Request.QueryString["ReturnUrl"]);
            //Response.Write(GetMD5Hash("123456"));
        }

        protected void LoginButton_Click(object sender, EventArgs e)
        {
            //Response.Write("<script>alert('Hello')</script>");
            string UserName = LoginUser.UserName;
            string Password = LoginUser.Password;
            User result = DoLogin(UserName, Password);
            if (result!=null)
            {
                Session["UserLogin"] = result;
                FormsAuthentication.SetAuthCookie(LoginUser.UserName, false /* createPersistentCookie */);
                string continueUrl = "~/Default.aspx";
                if (String.IsNullOrEmpty(continueUrl))
                {
                    continueUrl = "~/";
                }
                Response.Redirect(continueUrl);
                //Response.Redirect("~/Default.aspx?Logon=true");
            }
            else
            {
                return;
            }
        }

        // Password = '123456' == e10adc3949ba59abbe56e057f20f883e
        private User DoLogin(string username, string password)
        {
            User UserLogon = new User();
            try
            {
                dbLab8DataContext dbLab8 = new dbLab8DataContext();
                string md5Pass = GetMD5Hash(password);
                UserLogon = dbLab8.Users.Single(m=>m.Username==username && m.Password==md5Pass);
                //Set Cookie cho Loai User
                //FormsAuthentication.SetAuthCookie(UserLogon.IdRole.ToString(), false);
                //Session["IdRole"] = UserLogon.IdRole;
                return UserLogon;
            }
            catch
            {
                return null;
            }
        }

        private string GetMD5Hash(string input)
        {
            System.Security.Cryptography.MD5CryptoServiceProvider x = new System.Security.Cryptography.MD5CryptoServiceProvider();
            byte[] bs = System.Text.Encoding.UTF8.GetBytes(input);
            bs = x.ComputeHash(bs);
            System.Text.StringBuilder s = new System.Text.StringBuilder();
            foreach (byte b in bs)
            {
                s.Append(b.ToString("x2").ToLower());
            }
            string password = s.ToString();
            return password;
        }
    }
}
